package bluetooth;

import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Vector;

import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;

import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;

public class BlueComm implements DiscoveryListener {
    //目标服务标识

    private final static UUID TARGET_UUID = new UUID("F0E0D0C0B0A000908070605040302010", false);
    //存储发现的设备和服务的集合
    private Vector records = new Vector();
    //存储服务属性的集合
    private UUID[] uuidSet = null;
    //蓝牙发现代理类
    private DiscoveryAgent discoveryAgent = null;
    //服务搜索的事务id集合
    private int[] transIDs;
    //存活的服务索引
    int activeIndex = -1;
    //主界面
    private DataOutputStream dos = null;
    private RemoteDevice remotedevice = null;
    private String m_url = null;
    private boolean Connected = false;
    private StreamConnection conn = null;

    public BlueComm(RemoteDevice rd) {
        remotedevice = rd;
    }

    public BlueComm(String url) {
        m_url = url;
    }

    private boolean ConnectByUrl() {
        boolean result = false;

        try {
            System.out.println("connect by url: "+ m_url);
            conn = (StreamConnection) Connector.open(m_url);
            dos = conn.openDataOutputStream();
            dos.writeUTF("0");
            dos.flush();
            
            result = true;
        } catch (IOException e) {
            System.out.println("Error while accessing " + m_url);
        }
        return result;
    }

    private synchronized boolean ConnectByObject() {
        //如果初始化失败
        if (!initLocalDevice()) {
            System.out.println("bluetooth init failed~");
            //clientForm.appendInfo();
            return false;
        }

        //生成服务和属性的全球唯一标示符
        uuidSet = new UUID[2];
        uuidSet[0] = new UUID(0x1101);    //0x1101表示 采用btspp协议
        uuidSet[1] = TARGET_UUID;         //目标服务标示


        System.out.println("now begin to search service...");

        //遍历开启目标服务的蓝牙设备

        try {
            //记录每一次服务搜索的事务ID
            discoveryAgent.searchServices(null, uuidSet, remotedevice, this);
        } catch (BluetoothStateException ex) {
        }


        try {
            //阻塞，由serviceSearchCompleted函数回调唤醒
            wait();
        } catch (InterruptedException ex) {
            System.out.println(ex.getMessage());
            return false;
        }

        //添加显示信息
        System.out.println("service search finished~,find " + records.size() + " services");

        //如果搜索到了服务
        if (records.size() > 0) {
            activeIndex = getActiveService();
            if (activeIndex != -1) {
              
                return true;

            }
        } else {
            return false;

        }

        return false;

    }

    public synchronized boolean Connect() {
        if (!Connected) {
            if (remotedevice != null) {
                return (Connected=ConnectByObject());
            } else if (m_url != null) {
                return (Connected=ConnectByUrl());
            }

        }


        return false;

    }

    /**
     * 获取存活的服务索引
     * @return
     */
    private int getActiveService() {
        System.out.println(Integer.toString(records.size()));
        for (int i = 0; i < records.size(); i++) {
            ServiceRecord sr = (ServiceRecord) records.elementAt(i);
            if (accessService(sr, "0")) {
                return i;
            }
        }
        return -1;
    }

    public void disconnect() {
        System.out.println("disconnecting.");
        if (Connected) {
            sendMsg("Close_conn");
            Connected = false;
            try {
                dos.close();
                conn.close();
                System.out.println("disconnected..");

            } catch (IOException ex) {
            }


        }
    }

    /**
     * 初始化本地蓝牙设备
     * @return
     */
    private boolean initLocalDevice() {
        boolean isReady = false;
        try {
            LocalDevice localDevice = LocalDevice.getLocalDevice();

            discoveryAgent = localDevice.getDiscoveryAgent();

            //设置自身设备不可访问性
            localDevice.setDiscoverable(DiscoveryAgent.NOT_DISCOVERABLE);

            isReady = true;
        } catch (Exception ex) {
            isReady = false;
        }
        return isReady;
    }

    public void sendMsg(String msg) {
        try {

            dos.writeUTF(msg);
            dos.flush();
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }

    /**
     * 访问指定的服务
     * @param sr
     * @return
     */
    public String getUrl() {
        return m_url;

    }

    public String getDeviceName() {
        if (remotedevice != null) {
            try {
                return remotedevice.getFriendlyName(true);
            } catch (IOException ex) {
            }
        }
        return null;
    }

    public boolean accessService(ServiceRecord sr, String msg) {
        boolean result = false;

        try {

            m_url = sr.getConnectionURL(
                    ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
            System.out.println(m_url);
            conn = (StreamConnection) Connector.open(m_url);
            dos = conn.openDataOutputStream();
            dos.writeUTF(msg);

            dos.flush();
            result = true;
        } catch (IOException e) {
            System.out.println("Error while accessing " + m_url);
        }
        return result;
    }

    public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
        for (int i = 0; i < servRecord.length; i++) {
            records.addElement(servRecord[i]);
        }
    }

    public void serviceSearchCompleted(int transID, int respCode) {
        //遍历，并标志搜索到的服务
        synchronized (this) {
            notify();
        }

    }

    public void deviceDiscovered(RemoteDevice rd, DeviceClass dc) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void inquiryCompleted(int i) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
